package com.conan.app.dailyflickr.provider;

import java.sql.Date;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Locale;

import android.content.ContentValues;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.database.Cursor;
import android.net.Uri;
import android.text.TextUtils;
import android.util.Log;

import com.conan.app.flickrdaily.R;
import com.conan.app.dailyflickr.app.DailyPhotoData.Photo;
import com.conan.app.dailyflickr.provider.Constants.PHOTO_TABLE;
import com.conan.app.dailyflickr.provider.Constants.WIDGET_TABLE;

public class ProviderUtils {
	private static final String NULL_VALUE = "no_value";
	private static final String PREFS_NAME = "dailyPhotoPref";
	private static final String PREFS_NAME_ID = "daily_widget_id";

	/** set Preference **/
	/**
	 * id # id # id #
	 */
	public static void setWidgetUpdating(Context context, int widgetId){
		SharedPreferences settings = context.getSharedPreferences(PREFS_NAME, 0);
		
		SharedPreferences.Editor editor = settings.edit();
		
		String values = settings.getString(PREFS_NAME_ID, "");
		if(!TextUtils.isEmpty(values)){
			values.concat("#");
		}
		
		values.concat(Integer.toString(widgetId));
		editor.putString(PREFS_NAME_ID, values);

		// Commit the edits!
		editor.commit();
	}
	
	public static void deleteWidgetUpdating(Context context, int widgetId){
		SharedPreferences settings = context.getSharedPreferences(PREFS_NAME, 0);
		
		SharedPreferences.Editor editor = settings.edit();
		
		String values = settings.getString(PREFS_NAME_ID, "");
		if(!TextUtils.isEmpty(values)){
			String id = Integer.toString(widgetId);
			if(values.indexOf(id) > -1){
				values.replace(id, "");
			}
			values.replace("##", "#");
			if(values.endsWith("#") && values.length() > 0){
				values = values.substring(0, values.length() - 1);
			}
			editor.putString(PREFS_NAME_ID, values);
		}
		// Commit the edits!
		editor.commit();
	}
	
	public static int[] getWidgetUpdating(Context context){
		SharedPreferences settings = context.getSharedPreferences(PREFS_NAME, 0);
		String values = settings.getString(PREFS_NAME_ID, "");
		if(!TextUtils.isEmpty(values)){
			String[] rs = values.split("#");
			int size = rs.length;
			int[] ids = new int[size];
			for(int i =0; i < size; i++){
				ids[i] = Integer.parseInt(rs[i]);
			}
		}
		
		return null;
		// return settings.getInt(PREFS_NAME_ID, AppWidgetManager.INVALID_APPWIDGET_ID);
	}
	
	/** end set Preference **/
	static final String[] widget_projector = {
			WIDGET_TABLE._ID, WIDGET_TABLE._PAGE, WIDGET_TABLE._DATE, 
			WIDGET_TABLE._URL, WIDGET_TABLE._TITLE, WIDGET_TABLE._LAYOUT,
	};
	
	static final String[] photo_projector = {
		 PHOTO_TABLE._ID, WIDGET_TABLE._URL, WIDGET_TABLE._TITLE, 
		 /*PHOTO_TABLE._NO, PHOTO_TABLE._WIDGET_ID*/
	};
	

	/**
	 * 
		*  Aug 12, 2011
		*  @param context
		*  @param widgetId
		*  @param position
		*  @return
	 */
	public static boolean updatePhotoGetComplete(Context context, int widgetId, int position, Photo photo){
		
		return addPhotoToProvider(context, widgetId, position, photo);
		
	}
	
	
	/**
	 * 
		*  Aug 12, 2011
		*  @param context
		*  @param widgetId
		*  @param position
		*  @return
	 */
	public static Photo getPhotoFromProvider(Context context, int widgetId, int position){
		Photo photo = null;
		String where = PHOTO_TABLE._WIDGET_ID + "=? AND "  +
							PHOTO_TABLE._NO + "=?";
		String[] whereArgs = {Integer.toString(widgetId), Integer.toString(position)};
		
		Cursor cur = context.getContentResolver().query(Constants.CONTENT_PHOTO_URI,
								photo_projector, where, whereArgs, null);
		if(cur != null && cur.moveToFirst()){			
			photo = new Photo(cur.getString(0), cur.getString(1), cur.getString(2));
			
			cur.close();
		}
		
		return photo;
	}

	
	/**
	 * 
		*  Aug 12, 2011
		*  @param context
		*  @param widgetId
		*  @return
	 */
	public static ArrayList<Photo> getPhotosFromProvider(Context context, int widgetId){
		ArrayList<Photo> photos = new ArrayList<Photo>();
		
		
		String where = PHOTO_TABLE._WIDGET_ID + "=?"; 
		String[] whereArgs = {Integer.toString(widgetId)};
		
		Cursor cur = context.getContentResolver().query(Constants.CONTENT_PHOTO_URI,
					photo_projector, where, whereArgs, PHOTO_TABLE._NO);
		
		if(cur != null && cur.moveToFirst()){
			// Log.i(/*DailyPhotoData.TAG*/"@le.nguyen", String.format("-- getPhotosFromProvider ( size = %s ) --- ", cur.getCount()));
			do{
				
				Photo photo = new Photo(cur.getString(0), cur.getString(1), cur.getString(2));
				
				photos.add(photo);

			}while(cur.moveToNext());
			
			cur.close();
		}
		
		
		
		return photos;
	}
	
	public static boolean updatePhotoFromProvider(Context context, int widgetId, int position, Photo photo){
			ContentValues values = new ContentValues();
		   values.put(PHOTO_TABLE._ID, photo.mID);
		   values.put(PHOTO_TABLE._URL, photo.mUrl);
		   values.put(PHOTO_TABLE._TITLE, photo.mTitle);
		   
		   Photo query = getPhotoFromProvider(context, widgetId, position);
		   if(query == null){	// add new record
			   values.put(PHOTO_TABLE._NO, position);
			   values.put(PHOTO_TABLE._WIDGET_ID, widgetId);
			   Uri uri = context.getContentResolver().insert(
					   					Constants.CONTENT_PHOTO_URI, values);

			   return (uri != null)? true : false;
			   
		   }else{	// update record
		   
			   String where = PHOTO_TABLE._WIDGET_ID + "=?" +
			   PHOTO_TABLE._NO + "=?"; 
			   String[] whereArgs = {Integer.toString(widgetId), Integer.toString(position)};

			   int rs = context.getContentResolver().update( // uri, values, where, selectionArgs)(
					   Constants.CONTENT_PHOTO_URI , values, where, whereArgs);
			   return (rs < 0 )? false : true;
		   } 
		   
	}

	/**
	 * add widget info when has a widget enable
		*  Aug 15, 2011
		*  @param context
		*  @param widgetId
		*  @param position
		*  @param photo
		*  @return
	 */
	public static  boolean addPhotoToProvider(Context context, int widgetId, int position, Photo photo ){		  
			ContentValues values = new ContentValues();
		   values.put(PHOTO_TABLE._ID, photo.mID);
		   values.put(PHOTO_TABLE._URL, photo.mUrl);
		   values.put(PHOTO_TABLE._TITLE, photo.mTitle);
		   values.put(PHOTO_TABLE._NO, position);
		   values.put(PHOTO_TABLE._WIDGET_ID, widgetId);
		   
		   Photo old = getPhotoFromProvider(context, widgetId, position);
		   if(old == null) {	// add new record
			   
			   Uri uri = context.getContentResolver().insert(
				   								Constants.CONTENT_PHOTO_URI, values);
			   return (uri != null)? true : false;
			   
		   }else{	// update record
			   // Uri uri = Uri.withAppendedPath(Constants.CONTENT_PHOTO_URI, Integer.toString(info._id));
			   
			   int rs = context.getContentResolver().update( // uri, values, where, selectionArgs)(
					   										Constants.CONTENT_PHOTO_URI , values, null, null);
			   
			   return (rs < 0 )? false : true;
		   }
		  
	}

	private static final String TAG = "ProviderUtils";
	/**
	 * get local data of specific widget id
		*  Aug 15, 2011
		*  @param context
		*  @param widgetId
		*  @return
	 */
	public static DailyInfo getWidgetInfoFromProvider(Context context, int widgetId){
		Uri uri = Uri.withAppendedPath(Constants.CONTENT_URI, Integer.toString(widgetId));
		DailyInfo info = null;
		
		Cursor cur = context.getContentResolver().query(uri, widget_projector, null, null, null);	
		
		/*if(Constants.LOG){
			Log.d(TAG, "[uri] = " + uri.toString() );
		}*/
		
		if(cur != null && cur.moveToFirst()){
			
			String url = cur.getString(3);
			if(url.compareTo(NULL_VALUE) == 0) url = "";
			String title = cur.getString(4);
			if(title.compareTo(NULL_VALUE) == 0) title = "";

			info = new DailyInfo(cur.getInt(0), cur.getInt(1), cur.getLong(2),
										url , title, cur.getInt(5));
			
			cur.close();
		}else{
			Calendar cal = Calendar.getInstance(Locale.US);
			cal.add(Calendar.DATE, -1);
			info = new DailyInfo(widgetId, 1, cal, null, null, 0);
			addWidgetInfoToProvider(context, info);
		}
		
		return info;
	}
	/**
	 * update data for specific widget
		*  Aug 12, 2011
		*  @param context
		*  @param info
		*  @return
	 */
	public static boolean updateWidgetInfoToProvider(Context context, DailyInfo info){
		ContentValues values = new ContentValues();
		   values.put(WIDGET_TABLE._ID, info._id);
		   values.put(WIDGET_TABLE._PAGE, info._page);
		   values.put(WIDGET_TABLE._DATE,  info._date.getTimeInMillis());
		   values.put(WIDGET_TABLE._URL, info._url);
		   values.put(WIDGET_TABLE._TITLE, info._title);
		   values.put(WIDGET_TABLE._LAYOUT, info._layout);
		           
		  
			   
		   DailyInfo query = getWidgetInfoFromProvider(context, info._id);
		   if(query == null){	// add new record
			  
			   Uri uri = context.getContentResolver().insert(
					   					Constants.CONTENT_PHOTO_URI, values);

			   return (uri != null)? true : false;
			   
		   }else{	// update record
		   
			   Uri uri = Uri.withAppendedPath(Constants.CONTENT_URI, Integer.toString(info._id));
			   
			   int rs = context.getContentResolver().update( // uri, values, where, selectionArgs)(
					   											uri , values, null, null);
			
			   return (rs < 0 )? false : true;
		   } 
	}
	
	/**
	 * Aug 12, 2011
		*  add widget's info to database  
		*  @param context
		*  @param info
		*  @return
	 */
	public static  boolean addWidgetInfoToProvider(Context context, DailyInfo info ){
		   ContentValues values = new ContentValues();
		   values.put(WIDGET_TABLE._ID, info._id);
		   values.put(WIDGET_TABLE._PAGE, info._page);
		   values.put(WIDGET_TABLE._DATE, info._date.getTimeInMillis());
		   
		   values.put(WIDGET_TABLE._URL, TextUtils.isEmpty(info._url)?NULL_VALUE:info._url);
		   values.put(WIDGET_TABLE._TITLE, TextUtils.isEmpty(info._title)?NULL_VALUE:info._title);
		   
		   values.put(WIDGET_TABLE._LAYOUT, info._layout);
		           
		   Uri uri = context.getContentResolver().insert(
				   								Constants.CONTENT_URI, values);
		          
		   return (uri != null)? true : false;
	}

	/**
	 * @author @le.nguyen
		*  remove widget's info from database when there's widget was delete
		*  @param context
		*  @param info
		*  @return
	 */
	public static boolean deleteWidgetInfo(Context context, int appWidgetId ){
		 
		   Uri uri = Uri.withAppendedPath(Constants.CONTENT_URI, Integer.toString(appWidgetId));
		   int rs = context.getContentResolver().delete(uri, null, null);
		          
		   return (rs < 0)? false : true;
	}

	
	public static enum LAYOUT_TYPE_VALUE { normal, large};
	
	public static final int SIZE_PORTRAIT_NORMAL = 15;
	public static final int SIZE_PORTRAIT_LARGE = 8;
	public static final int SIZE_LANDSCAPE = 12;
	public static final int SIZE_LANDSCAPE_LARGE = 6;

	// ------------------------
	public static class LayoutType{
		public int _PER_PAGE;
		public int _layoutId;
		
		public LayoutType(Context context, LAYOUT_TYPE_VALUE type) {
			if(type == null){
				type = LAYOUT_TYPE_VALUE.normal ;
			}

			boolean portrait = true;
			if (context.getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
				portrait = false;
			}
			
		
			switch (type) {
			case large:
				// Query what the orientation currently really is.
				if(portrait){
					this._layoutId = R.layout.flickr_widget_large;
					this._PER_PAGE = SIZE_PORTRAIT_LARGE;
				}else{
					this._layoutId = R.layout.flickr_widget_land_large;
					this._PER_PAGE = SIZE_LANDSCAPE_LARGE;
				}
				
				break;
			default:
				if(portrait){
					this._layoutId = R.layout.flickr_widget;
					this._PER_PAGE = SIZE_PORTRAIT_NORMAL;
				}else{
					this._layoutId = R.layout.flickr_widget_land;
					this._PER_PAGE = SIZE_LANDSCAPE;
				}
			}
		}
		
		public LayoutType(Context context, int type){
			this(context, LAYOUT_TYPE_VALUE.values()[type]);
		}
	}
	/**
	 * store the infomation for loading page for specific widget Id
	 */
	public static class DailyInfo{
		public int _page;
		public Calendar _date;
		public String _url;
		public String _title;
		public int _id;
		public int _layout;
		
		public DailyInfo(int id, int page, long date, String url, String title, int layout) {
			this(id, page, Calendar.getInstance(), url, title, layout);

			Date day = new Date(date);
			_date.setTime(day);
		}
		
		public DailyInfo(int id, int page, Calendar date, String url, String title, int layout) {
			_page = page;
			_date = date;
			_url = (TextUtils.isEmpty(url)? "" : url);
			_title = (TextUtils.isEmpty(url)? "" : title);
			_id = id;
			_layout = layout;
		}

		/**
		 * @author @le.nguyen
			*  TODO
			*  @param @param info
		 */
		public void setInfo(DailyInfo info) {
			_page = info._page;
			_date = info._date;
			_url = info._url;
			_title = info._title;
			_id = info._id;
			_layout = info._layout;
		}    	
	}
	

}
